/*
 * Seq_File Example (linux-5.10)
 * from: https://lwn.net/Articles/22359/
 * dd if=/proc/myseq of=out1 count=1  //0-155, 最后一个数字不完整
 * dd if=/proc/myseq skip=1 of=out2 count=1  //156-283, 最后一个数字不完整
 *
 */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>

#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/seq_file.h>
#include <linux/slab.h>

static struct proc_dir_entry *my_proc_entry;

//每一次用户的读写操作，会初始化一个session, 此时会调用start操作
static void *my_seq_start(struct seq_file *seq, loff_t *pos)
{
	loff_t *sess_pos;

	//pr_info("%s: pos=%lld\n", __func__, *pos);

	sess_pos = kmalloc(sizeof(loff_t), GFP_KERNEL);
	if (!sess_pos)
		return NULL;
	*sess_pos = *pos;
	return sess_pos;
}

static void my_seq_stop(struct seq_file *seq, void *v)
{
	kfree(v);
}

static void *my_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
	loff_t *sess_pos = (loff_t*)v;

	//pr_info("%s: pos=%lld, sess_pos=%lld\n", __func__, *pos, *sess_pos);

	*pos = ++(*sess_pos); //session指针需要更新
	return sess_pos;
}

static int my_seq_show(struct seq_file *seq, void *v)
{
	loff_t *sess_pos = (loff_t*)v;
	seq_printf(seq, "%Ld\n", *sess_pos); //读取指针所在的位置
	return 0;
}

static struct seq_operations my_seq_fops = {
	.start = my_seq_start,
	.stop = my_seq_stop,
	.next = my_seq_next,
	.show = my_seq_show,
};

static int my_seqfile_open(struct inode *inode, struct file *flip)
{
	return seq_open(flip, &my_seq_fops);
}

static const struct proc_ops my_proc_ops = {
	.proc_open = my_seqfile_open,  //only implement open
	.proc_read = seq_read,
	.proc_lseek = seq_lseek,
	.proc_release = seq_release,
};


static int __init my_seqfile_init(void)
{
	pr_info("%s...\n", __func__);

	my_proc_entry = proc_create("myseq", 0664, NULL, &my_proc_ops);
	if (!my_proc_entry) {
		pr_err("proc_create failed\n");
		return -ENOMEM;
	}

	return 0;
}

static void __exit my_seqfile_exit(void)
{
	pr_info("%s...\n", __func__);

	if (my_proc_entry)
		proc_remove(my_proc_entry);
}

module_init(my_seqfile_init);
module_exit(my_seqfile_exit);

MODULE_LICENSE("GPL");
